from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
from models.commit_message_model import CommitMessageModel
from monitoring.decorators import monitor_api_endpoint, monitor_model_generation
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter()

# 延迟初始化模型
commit_model = None

def get_commit_model():
    """获取CommitMessageModel实例（延迟初始化）"""
    global commit_model
    if commit_model is None:
        # 确保在创建模型之前禁用Langfuse自动集成
        import os
        os.environ["LANGFUSE_OPENAI_INTEGRATION"] = "false"
        os.environ["LANGFUSE_AUTO_INSTRUMENT"] = "false"
        os.environ["OPENAI_LANGFUSE_PUBLIC_KEY"] = ""
        os.environ["OPENAI_LANGFUSE_SECRET_KEY"] = ""
        os.environ["OPENAI_LANGFUSE_HOST"] = ""
        
        from models.commit_message_model import CommitMessageModel
        commit_model = CommitMessageModel()
    return commit_model

# 请求和响应模型
class SummaryItem(BaseModel):
    order: int
    summary: str

class SummarizeRequest(BaseModel):
    summaries: List[SummaryItem]
    user_id: Optional[str] = None
    session_id: Optional[str] = None

class SummarizeResponse(BaseModel):
    result: str
    commit_count: int
    files_affected: int
    change_types: List[str]
    model_used: str
    timestamp: str

# 生成汇总commit message路由
@router.post("/summarize", response_model=SummarizeResponse)
@monitor_api_endpoint("commit_summarize")
@monitor_model_generation("commit_message_model")
async def summarize_commits(
    request: SummarizeRequest,
    user_id: Optional[str] = Query(None, description="用户ID，用于追踪（URL参数）"),
    session_id: Optional[str] = Query(None, description="会话ID，用于追踪（URL参数）")
):
    """根据多个summary信息生成一条汇总的commit message"""
    try:
        # 优先使用请求体中的参数，如果没有则使用URL参数
        final_user_id = request.user_id or user_id
        final_session_id = request.session_id or session_id
        
        # 打印详细的请求参数
        logger.info("=== 收到汇总请求 ===")
        logger.info(f"🔍 请求体中的参数 - user_id: {request.user_id}, session_id: {request.session_id}")
        logger.info(f"🔍 URL查询参数 - user_id: {user_id}, session_id: {session_id}")
        logger.info(f"✅ 最终使用的参数 - user_id: {final_user_id}, session_id: {final_session_id}")
        logger.info(f"📋 完整请求体: {request}")
        logger.info(f"📊 summaries数量: {len(request.summaries)}")
        
        for i, summary in enumerate(request.summaries):
            logger.info(f"Summary {i+1}: order={summary.order}, content='{summary.summary}'")
        
        # 转换为字典格式
        summaries_dict = [{"order": item.order, "summary": item.summary} for item in request.summaries]
        logger.info(f"转换后的数据: {summaries_dict}")
        
        # 调用模型生成结果，传递追踪参数
        logger.info("开始生成汇总commit message...")
        model = get_commit_model()
        result = model.generate_structured_summary(
            summaries_dict,
            user_id=final_user_id,
            session_id=final_session_id
        )
        
        logger.info("=== 生成结果 ===")
        logger.info(f"生成的commit message: {result.get('result', 'N/A')}")
        logger.info(f"变更类型: {result.get('change_types', [])}")
        logger.info(f"影响文件数: {result.get('files_affected', 0)}")
        
        return SummarizeResponse(**result)
    except Exception as e:
        logger.error(f"生成汇总commit message失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"生成汇总commit message失败: {str(e)}")

# 健康检查
@router.get("/health")
@monitor_api_endpoint("commit_health_check")
async def health_check():
    """健康检查"""
    logger.info("收到健康检查请求")
    model = get_commit_model()
    return {
        "status": "healthy",
        "service": "Commit Message Summary Generator",
        "model": model.model_name
    } 